<template>
  <!-- <bread-crumb></bread-crumb> -->
  <!-- <x-card
    :message="message_card"
    :width="98"
    :height="850"
    style="margin: 20px 20px;"
  > -->
  <!-- 搜索以及操作 -->
  <!-- 自定义组件 -->
  <x-search>
    <!-- 搜索的一系列东西 -->
    <template #search>
      <p>
        <a-input
          v-model:value="exam_name"
          placeholder="查询考试名称"
          style="width: 150px"
        />
      </p>
      <p style="margin-left: 10px">
        <a-select
          v-model:value="class_id"
          placeholder="查询班级"
          style="width: 120px"
        >
          <a-select-option
            v-for="(value, index) in all_classes"
            :key="index"
            :value="value.id"
          >
            <span>{{ value.name }}</span>
          </a-select-option>
        </a-select>
      </p>
      <p style="margin-left: 10px">
        <a-select
          v-model:value="program_id"
          placeholder="查询专业"
          style="width: 120px"
        >
          <a-select-option
            v-for="(value, index) in all_programs"
            :key="index"
            :value="value.id"
          >
            <span>{{ value.name }}</span>
          </a-select-option>
        </a-select>
      </p>
      <p style="margin-left: 10px">
        <a-range-picker
          v-model:value="exam_date"
          show-time
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          :placeholder="['考试开始时间','考试结束时间']"
          style="width: 300px"
        />
      </p>
      <p style="margin-left: 10px">
        <a-select
          v-model:value="exam_type"
          placeholder="查询考试类型"
          style="width: 150px"
        >
          <a-select-option :value="1">周考</a-select-option>
          <a-select-option :value="0">月考</a-select-option>
          <a-select-option :value="2">年考</a-select-option>
        </a-select>
      </p>
      <a-button type="primary" style="margin-left: 10px" @click="but_search"
        >搜索</a-button
      >
      <a-button style="margin-left: 10px" @click="reset_search">重置</a-button>
      <a-button style="margin-left: 10px" @click="Refresh">刷新数据</a-button>
    </template>
    <!-- 操作的一系列东西 -->
    <template #operate>
      <a-button
        type="primary"
        style="margin-left: 10px"
        @click="showModal_add"
        v-checkpermission:foo.bar="'exam_add'"
      >
        <template #icon><plus-outlined style="margin-right: 0" /></template>
        新增考试</a-button
      >
    </template>
  </x-search>
  <!-- 谈话框--添加权限 -->
  <a-drawer v-model:open="open_add" title="新增考试" width="500">
    <a-form
      ref="formRef"
      :model="formState"
      :rules="rules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <a-form-item label="考试名称" name="name">
        <a-input v-model:value="formState.name" placeholder="请输入考试名称" />
      </a-form-item>

      <a-form-item label="考试类型" name="type">
        <!-- // 考试类型： 1 周考；0 月考；2 年考 -->
        <a-select v-model:value="formState.type" placeholder="请选择考试类型">
          <a-select-option :value="1">周考</a-select-option>
          <a-select-option :value="0">月考</a-select-option>
          <a-select-option :value="2">年考</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="班级" name="class_id">
        <a-select
          v-model:value="formState.class_id"
          placeholder="查询班级"
          style="width: 120px"
        >
          <a-select-option
            v-for="(value, index) in all_classes"
            :key="index"
            :value="value.id"
          >
            <span>{{ value.name }}</span>
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="考试时间" name="date">
        <a-date-picker
          v-model:value="formState.date"
          show-time
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="请选择考试日期时间"
          style="width: 100%"
        />
      </a-form-item>

      <a-form-item label="占比" name="sort">
        <span style="line-height: 40px">笔试占比</span>&nbsp;&nbsp;
        <a-form-item name="sort" no-style label="笔试占比">
          <a-input-number
            v-model:value="formState.write_of"
            :min="0"
            :max="100"
          /> </a-form-item
        ><br />
        <span style="line-height: 40px">机试占比</span>&nbsp;&nbsp;
        <a-form-item name="sort" no-style label="机试占比">
          <a-input-number
            v-model:value="formState.practe_of"
            :min="0"
            :max="100"
          /> </a-form-item
        ><br />
        <span style="line-height: 40px">面试占比</span>&nbsp;&nbsp;
        <a-form-item name="sort" no-style label="面试占比">
          <a-input-number
            v-model:value="formState.meet_of"
            :min="0"
            :max="100"
          /> </a-form-item
        ><br />
        <span style="line-height: 40px">项目占比</span>&nbsp;&nbsp;
        <a-form-item name="sort" no-style label="项目占比">
          <a-input-number
            v-model:value="formState.project_of"
            :min="0"
            :max="100"
          /> </a-form-item
        ><br />
        <span style="color: #ccc; font-size: 14px"
          >总占比:{{ formState.all_of }}%</span
        >
      </a-form-item>

      <a-form-item label="备注" name="notes">
        <a-input v-model:value="formState.notes" placeholder="请输入备注" />
      </a-form-item>
    </a-form>

    <template #footer>
      <a-button @click="handleCancel">取消</a-button>
      <a-button type="primary" @click="handleSubmit" style="margin-left: 10px"
        >提交</a-button
      >
    </template>
  </a-drawer>
  <!-- 搜索下面的表格 -->
  <a-table
    :dataSource="dataSource"
    :columns="columns"
    :loading="loading"
    :pagination="{
      pageSize: state.pageSize,
      total: state.total,
      current: state.current,
      showSizeChanger: true, // 显示每页条数选择器
      pageSizeOptions: ['10', '20', '50'], // 自定义每页条数选项
      showTotal: (total) => `共 ${total} 条`, // 显示总条数
    }"
    @change="
      (pagination) => {
        console.log(pagination);
        state.pageSize = pagination.pageSize;
        state.total = pagination.total;
        state.current = pagination.current;
      }
    "
    :scroll="{ y: 600 }"
  >
    <!-- :columns="columns" :data-source="data" @resizeColumn="handleResizeColumn" -->
    <!-- 头部表头默认显示，不需要操作 -->
    <!-- <template #headerCell="{ column }"></template> -->
    <!-- 身体-表格中的列表 -->
    <!-- <template #bodyCell="{ column, record }"> -->
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'student_count'">
        <!-- 未统计状态 -->
        <a-tag
          v-if="record.student_count == null || record.student_count === ''"
          :bordered="false"
          color="error"
        >
          暂未统计
        </a-tag>

        <!-- 已统计状态 -->
        <a-tag
          v-else
          :bordered="false"
          :color="getStudentCountColor(record.student_count)"
        >
          {{ record.student_count }}人
        </a-tag>
      </template>
      <template v-if="column.key === 'average_score'">
        <!-- 未统计状态 -->
        <a-tag
          v-if="record.average_score == null || record.average_score === ''"
          :bordered="false"
          color="error"
        >
          暂未统计
        </a-tag>

        <!-- 已统计状态 -->
        <a-tag
          v-else
          :bordered="false"
          :color="getAverageScoreColor(record.average_score)"
        >
          {{ record.average_score }}分
        </a-tag>
      </template>
      <template v-if="column.key === 'total_score'">
        <!-- 未统计状态 -->
        <a-tag
          v-if="record.total_score == null || record.total_score === ''"
          :bordered="false"
          color="error"
        >
          暂未统计
        </a-tag>

        <!-- 已统计状态 -->
        <a-tag
          v-else
          :bordered="false"
          :color="getTotalScoreColor(record.total_score)"
        >
          {{ record.total_score }}分
        </a-tag>
      </template>
      <template v-if="column.key === 'type'">
        <!-- 考试类型： 1 周考；0 月考；2 年考 -->
        <span v-if="record.type == 1">
          <a-tag color="cyan">周考</a-tag>
        </span>
        <span v-if="record.type == 0">
          <a-tag color="green">月考</a-tag>
        </span>
        <span v-if="record.type == 2">
          <a-tag color="blue">年考</a-tag>
        </span>
      </template>
      <template v-else-if="column.key === 'action'">
        <a-space>
          <!-- 查看按钮 -->
          <a-tooltip title="查看" placement="top">
            <a-button
              type="text"
              size="small"
              @click="showModal_view(record.id)"
              v-checkpermission:foo.bar="'exam_list'"
            >
              <template #icon>
                <EyeOutlined style="color: #91959c" />
              </template>
            </a-button>
          </a-tooltip>

          <!-- 考试记录按钮 -->
          <a-tooltip title="查看考试记录" placement="top">
            <a-button
              type="text"
              size="small"
              @click="exam_record(record)"
              v-checkpermission:foo.bar="'exam_list'"
            >
              <template #icon>
                <FileTextOutlined style="color: #722ed1" />
              </template>
            </a-button>
          </a-tooltip>

          <!-- 编辑按钮 -->
          <a-tooltip title="编辑" placement="top">
            <a-button
              type="text"
              size="small"
              @click="showModal_edit(record.id)"
              v-checkpermission:foo.bar="'exam_edit'"
            >
              <template #icon>
                <EditOutlined style="color: #52c41a" />
              </template>
            </a-button>
          </a-tooltip>

          <!-- 考试总数统计 -->
          <a-tooltip title="总数统计" placement="top">
            <a-button
              type="text"
              size="small"
              @click="total_count(record)"
              v-checkpermission:foo.bar="'exam_edit'"
            >
              <template #icon>
                <AreaChartOutlined style="color: #52c41a" />
              </template>
            </a-button>
          </a-tooltip>

          <!-- 考试平均数统计 -->
          <a-tooltip title="平均数及总录入数统计" placement="top">
            <a-button
              type="text"
              size="small"
              @click="count_average(record)"
              v-checkpermission:foo.bar="'exam_edit'"
            >
              <template #icon>
                <LineChartOutlined style="color: #52c41a" />
                <!-- <AreaChartOutlined style="color: #52c41a" /> -->
              </template>
            </a-button>
          </a-tooltip>

          <!-- 成绩录入按钮 -->
          <a-tooltip title="成绩录入" placement="top">
            <a-button
              type="text"
              size="small"
              @click="count_record(record)"
              v-checkpermission:foo.bar="'exam_set'"
            >
              <template #icon>
                <FormOutlined style="color: #fa8c16" />
              </template>
            </a-button>
          </a-tooltip>

          <!-- 状态切换按钮 -->
          <a-tooltip
            :title="record.state_del === 0 ? '禁用' : '启用'"
            placement="top"
          >
            <a-button
              type="text"
              size="small"
              :danger="record.state_del === 0"
              @click="
                record.state_del === 0
                  ? del_exam_f(record.id)
                  : start_state(record.id)
              "
              v-checkpermission:foo.bar="'exam_delete'"
            >
              <template #icon>
                <DeleteOutlined
                  :style="{
                    color: record.state_del === 0 ? '#ff4d4f' : '#52c41a',
                  }"
                />
              </template>
            </a-button>
          </a-tooltip>

          <!-- 真删除按钮 -->
          <a-tooltip v-if="record.state_del === 1" title="删除" placement="top">
            <a-button
              type="text"
              size="small"
              danger
              @click="del_exam_t(record.id)"
              v-checkpermission:foo.bar="'exam_delete'"
            >
              <template #icon>
                <DeleteOutlined style="color: #cf1322" />
              </template>
            </a-button>
          </a-tooltip>

          <!-- 统计分析按钮 -->
          <a-tooltip title="统计分析" placement="top">
            <a-button type="text" size="small" @click="exam_search(record.id)">
              <template #icon>
                <BarChartOutlined style="color: #13c2c2" />
              </template>
            </a-button>
          </a-tooltip>
        </a-space>
      </template>
    </template>
  </a-table>
  <!-- 谈话框--编辑考试信息 -->
  <a-drawer v-model:open="open_edit" title="修改考试信息" width="500">
    <a-form
      ref="formRef_edit"
      :model="formState_edit"
      :rules="rules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <a-form-item label="考试名称" name="name">
        <a-input v-model:value="formState_edit.name" />
      </a-form-item>
      <a-form-item label="考试类型" name="type">
        <!-- // 考试类型： 1 周考；0 月考；2 年考 -->
        <a-select
          v-model:value="formState_edit.type"
          placeholder="请选择考试类型"
        >
          <a-select-option :value="1">周考</a-select-option>
          <a-select-option :value="0">月考</a-select-option>
          <a-select-option :value="2">年考</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="班级" name="class_id">
        <a-select
          v-model:value="formState_edit.class_id"
          placeholder="查询班级"
          style="width: 120px"
        >
          <a-select-option
            v-for="(value, index) in all_classes"
            :key="index"
            :value="value.id"
          >
            <span>{{ value.name }}</span>
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="考试日期" name="date">
        <a-date-picker
          v-model:value="formState_edit.date"
          v-model:open="open_date"
          show-time
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="请选择考试日期时间"
          style="width: 100%"
        >
          <template #renderExtraFooter>
            <a-button size="small" type="primary" @click="handleClose"
              >取消</a-button
            >
          </template>
        </a-date-picker>
      </a-form-item>

      <a-form-item label="总分" name="total_score">
        <a-input v-model:value="formState_edit.total_score" />
      </a-form-item>

      <a-form-item label="占比" name="sort">
        <span style="line-height: 40px">笔试占比</span>&nbsp;&nbsp;
        <a-form-item name="sort" no-style label="笔试占比">
          <a-input-number
            v-model:value="formState_edit.write_of"
            :min="0"
            :max="100"
          /> </a-form-item
        ><br />
        <span style="line-height: 40px">机试占比</span>&nbsp;&nbsp;
        <a-form-item name="sort" no-style label="机试占比">
          <a-input-number
            v-model:value="formState_edit.practe_of"
            :min="0"
            :max="100"
          /> </a-form-item
        ><br />
        <span style="line-height: 40px">面试占比</span>&nbsp;&nbsp;
        <a-form-item name="sort" no-style label="面试占比">
          <a-input-number
            v-model:value="formState_edit.meet_of"
            :min="0"
            :max="100"
          /> </a-form-item
        ><br />
        <span style="line-height: 40px">项目占比</span>&nbsp;&nbsp;
        <a-form-item name="sort" no-style label="项目占比">
          <a-input-number
            v-model:value="formState_edit.project_of"
            :min="0"
            :max="100"
          /> </a-form-item
        ><br />
        <span style="color: #ccc; font-size: 14px"
          >总占比:{{ formState_edit.all_of }}%</span
        >
      </a-form-item>
      <a-form-item label="备注" name="notes">
        <a-input
          v-model:value="formState_edit.notes"
          placeholder="请输入备注"
        />
      </a-form-item>
    </a-form>
    <template #footer>
      <a-button @click="handleCancel_edit">取消</a-button>
      <a-button type="primary" @click="handleOk_edit" style="margin-left: 10px"
        >提交</a-button
      >
    </template>
  </a-drawer>
  <!-- 谈话框--查看考试信息 -->
  <a-drawer v-model:open="open_view" title="查看考试信息" width="500">
    <a-form
      ref="formRef_edit"
      :model="formState_edit"
      :rules="rules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <a-form-item label="考试名称" name="name">
        {{ formState_edit.name }}
      </a-form-item>
      <a-form-item label="考试类型" name="type">
        <!-- 考试类型： 1 周考；0 月考；2 年考 -->
        <span v-if="formState_edit.type == 1">周考</span>
        <span v-if="formState_edit.type == 0">月考</span>
        <span v-if="formState_edit.type == 2">年考</span>
      </a-form-item>

      <a-form-item label="班级" name="class_name">
        {{ formState_edit.class_name }}
      </a-form-item>

      <a-form-item label="考试日期" name="date">
        <a-date-picker v-model:value="formState_edit.date" disabled />
      </a-form-item>

      <a-form-item label="总分" name="total_score">
        <a-tag
          :bordered="false"
          color="error"
          v-if="
            formState_edit.total_score == '' ||
            formState_edit.total_score == null
          "
          >暂未统计</a-tag
        >
      </a-form-item>

      <a-form-item label="占比" name="sort">
        <span style="line-height: 40px">笔试占比</span>&nbsp;&nbsp;
        <a-form-item name="sort" no-style label="笔试占比">
          {{ formState.write_of }}%</a-form-item
        ><br />
        <span style="line-height: 40px">机试占比</span>&nbsp;&nbsp;
        <a-form-item name="sort" no-style label="机试占比">
          {{ formState.practe_of }}%</a-form-item
        ><br />
        <span style="line-height: 40px">面试占比</span>&nbsp;&nbsp;
        <a-form-item name="sort" no-style label="面试占比">
          {{ formState.meet_of }}%</a-form-item
        ><br />
        <span style="line-height: 40px">项目占比</span>&nbsp;&nbsp;
        <a-form-item name="sort" no-style label="项目占比">
          {{ formState.project_of }}%</a-form-item
        ><br />
        <span style="color: #ccc; font-size: 14px"
          >总占比:{{ formState.all_of }}%</span
        >
      </a-form-item>
      <a-form-item label="备注" name="notes">
        {{ formState_edit.notes }}
      </a-form-item>
    </a-form>
  </a-drawer>
  <!-- 抽屉--考试记录 -->
  <a-drawer v-model:open="open_exam" title="考试记录" width="900">
    <p style="text-align: center; font-size: 18px">
      {{ formState_edit.name }}-考试记录
    </p>
    <p style="text-align: center; color: #ccc">
      笔试:{{ formState_edit.write_of }}%;机试:{{
        formState_edit.practe_of
      }}%;面试:{{ formState_edit.meet_of }}%;项目:{{
        formState_edit.project_of
      }}%;
    </p>
    <a-table
      style="margin-top: 20px"
      :dataSource="dataSource_exam"
      :columns="columns_exam"
      :pagination="{
        pageSize: state2.pageSize,
        total: state2.total,
        current: state2.current,
        showSizeChanger: true, // 显示每页条数选择器
        pageSizeOptions: ['10', '20', '50'], // 自定义每页条数选项
        showTotal: (total) => `共 ${total} 条`, // 显示总条数
      }"
      @change="
        (pagination) => {
          console.log(pagination);
          state2.pageSize = pagination.pageSize;
          state2.total = pagination.total;
          state2.current = pagination.current;
        }
      "
    >
    </a-table>
  </a-drawer>
  <!-- 抽屉--成绩录入 -->
  <a-drawer v-model:open="open_count" title="成绩录入" width="1200">
    <p style="text-align: center; font-size: 18px">
      {{ formState_edit.name }}-成绩录入
    </p>
    <p style="text-align: center; color: #ccc">
      笔试:{{ formState_edit.write_of }}%;机试:{{
        formState_edit.practe_of
      }}%;面试:{{ formState_edit.meet_of }}%;项目:{{
        formState_edit.project_of
      }}%;
    </p>
    <a-table
      style="margin-top: 20px"
      :dataSource="dataSource_count"
      :columns="columns_count"
      :pagination="{
        pageSize: state3.pageSize,
        total: state3.total,
        current: state3.current,
        showSizeChanger: true, // 显示每页条数选择器
        pageSizeOptions: ['10', '20', '50'], // 自定义每页条数选项
        showTotal: (total) => `共 ${total} 条`, // 显示总条数
      }"
      @change="
        (pagination) => {
          console.log(pagination);
          state3.pageSize = pagination.pageSize;
          state3.total = pagination.total;
          state3.current = pagination.current;
        }
      "
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'score_write'">
          <a-input-number
            id="inputNumber"
            v-model:value="record.score_write"
            :min="0"
            :max="100"
          />
        </template>
        <template v-if="column.key === 'score_practe'">
          <a-input-number
            id="inputNumber"
            v-model:value="record.score_practe"
            :min="0"
            :max="100"
          />
        </template>
        <template v-if="column.key === 'score_meet'">
          <a-input-number
            id="inputNumber"
            v-model:value="record.score_meet"
            :min="0"
            :max="100"
          />
        </template>
        <template v-if="column.key === 'score_project'">
          <a-input-number
            v-if="formState_edit.project_of == 0"
            id="inputNumber"
            v-model:value="record.score_project"
            :min="0"
            :max="100"
            :disabled="true"
          />
          <a-input-number
            v-else
            id="inputNumber"
            v-model:value="record.score_project"
            :min="0"
            :max="100"
          />
        </template>
        <template v-if="column.key === 'comment'">
          <a-input v-model:value="record.comment" />
        </template>
        <template v-if="column.key === 'action'">
          <a-button type="primary" @click="enter_count(record)"
            >确定录入</a-button
          >
        </template>
      </template>
    </a-table>
  </a-drawer>
  <!-- </x-card> -->
</template>

<script lang="ts" setup>
import XSearch from "./XSearch.vue";
import {
  ref,
  reactive,
  toRaw,
  onMounted,
  createVNode,
  watch,
  computed,
} from "vue";
import http from "../routerutils/http";
import { message, Modal, Cascader } from "ant-design-vue";
// 对话提示
import {
  ExclamationCircleOutlined,
  EyeOutlined, // 查看图标
  EditOutlined, // 编辑图标
  FileTextOutlined, // 考试记录图标
  FormOutlined, // 成绩录入图标
  DeleteOutlined, // 删除图标
  BarChartOutlined, // 统计分析图标
  PlusOutlined,
  DownloadOutlined,
  AreaChartOutlined,
  LineChartOutlined,
} from "@ant-design/icons-vue";
// 表单验证
import type { Rule } from "ant-design-vue/es/form";
import type { UnwrapRef } from "vue";
import type { CascaderProps } from "ant-design-vue";
import { number } from "echarts";
import type { Dayjs } from "dayjs";
// 处理时间
import dayjs from "dayjs";
import router from "@/router";
import { useStore } from "vuex";
const store = useStore();
const userPermiss_vuex = store.state.userPermiss;
// 创建一个自定义指令，来统一处理权限存在与否
const vCheckpermission = {
  mounted: (el: any, binding: any) => {
    if (!userPermiss_vuex.includes(binding.value)) {
      // 移除元素
      el.parentNode?.removeChild(el);
    }
    console.log(el, binding);
    // el.classList.add("is-highlight");
  },
};

// 统计分析的跳转
const exam_search = (id:number) => {
  router.push(`/admin/count/overview?class_id=${id}`);
};

// 根据分数返回对应的颜色
const getAverageScoreColor = (score: any) => {
  const num = parseFloat(score);
  if (isNaN(num)) return "default";

  if (num >= 90) return "success"; // 优秀 - 绿色
  if (num >= 80) return "processing"; // 良好 - 蓝色
  if (num >= 60) return "warning"; // 及格 - 橙色
  return "error"; // 不及格 - 红色
};

// 根据总分返回对应的颜色
const getTotalScoreColor = (score: any) => {
  const num = parseFloat(score);
  if (isNaN(num)) return "default";

  if (num >= 1000) return "#722ed1"; // 紫色 - 非常优秀
  if (num >= 800) return "success"; // 绿色 - 优秀
  if (num >= 600) return "processing"; // 蓝色 - 良好
  if (num >= 400) return "cyan"; // 青色 - 中等
  if (num >= 200) return "warning"; // 橙色 - 及格
  return "error"; // 红色 - 不及格
};

// 根据学生人数返回对应的颜色
const getStudentCountColor = (count: any) => {
  const num = parseInt(count);
  if (isNaN(num)) return "default";

  if (num > 100) return "#722ed1"; // 紫色 - 超大规模
  if (num > 80) return "#eb2f96"; // 粉红色 - 大规模
  if (num > 60) return "success"; // 绿色 - 较大规模
  if (num > 40) return "processing"; // 蓝色 - 中等规模
  if (num > 20) return "cyan"; // 青色 - 小规模
  if (num > 10) return "orange"; // 橙色 - 较小规模
  return "error"; // 红色 - 极小规模
};

// x-card组件需要的属性
const message_card = ref<string>("");
// const height = ref<string>("850px");
// 日期的取消按钮
const open_date = ref<boolean>(false);
const handleClose = () => {
  open_date.value = false;
};
// 1. 搜索相关的操作数据
const exam_name = ref<string>("");
const class_id = ref();
const program_id = ref();
const exam_date = ref<string[]>([]);
const exam_type = ref();

const reset_search = () => {
  state.current = 1;
  exam_name.value = "";
  class_id.value = null;
  program_id.value = null;
  exam_date.value = [];
  exam_type.value = null;
  test_list();
};
const Refresh = () => {
  // state.current = 1
  test_list();
};
// 搜索按钮的方法
const but_search = () => {
  //   permis_list();
  test_list();
};
interface ClassInfo {
  id: string;
  name: string;
}
// 后端接口所有班级数据
const all_classes = ref<ClassInfo[]>([]);
const all_class = async () => {
  try {
    const response = await http.get("/api/students/allclass");
    console.log(response.data.results);
    all_classes.value = response.data.results;
  } catch (error) {
    console.log("请求失败：：", error);
  }
};
// 后端接口所有专业数据
const all_programs = ref<ClassInfo[]>([]);
const all_program = async () => {
  try {
    const response = await http.get("/api/students/allprogram");
    console.log(response.data.results);
    all_programs.value = response.data.results;
  } catch (error) {
    console.log("请求失败：：", error);
  }
};
// 2. 新增考试按钮的相关操作
// 谈话窗是否展示
const open_add = ref<boolean>(false);
const labelCol = { span: 5 };
const wrapperCol = { span: 13 };
const formRef = ref();
// 添加考试接口
const add_exam = async () => {
  // name, type, class_id, date, notes, total_score, write_of, practe_of, meet_of,project_of
  // 考试类型： 1 周考；0 月考；2 年考
  try {
    const response = await http.post("/api/tests/add", {
      name: formState.name,
      type: formState.type,
      class_id: formState.class_id,
      date: dayjs(formState.date).format("YYYY-MM-DD HH:mm:ss"),
      notes: formState.notes,
      write_of: formState.write_of,
      practe_of: formState.practe_of,
      meet_of: formState.meet_of,
      project_of: formState.project_of,
    });
    if (response.data.code === 0) {
      test_list();
      message.success(response.data.msg);
    } else {
      message.error(response.data.msg);
    }
  } catch (error) {
    console.log("请求失败：：", error);
  }
};
// 接口--修改和添加用一样的接口
interface FormState {
  name: string;
  type: number;
  class_id: number;
  date: Dayjs;
  notes: string;
  total_score: string;
  write_of: number;
  practe_of: number;
  meet_of: number;
  project_of: number;
  all_of: number;
  class_name?: string;
}
// 表单元素
const formState: UnwrapRef<FormState> = reactive({
  name: "",
  type: null,
  class_id: null,
  date: "",
  notes: "",
  total_score: "",
  write_of: 20,
  practe_of: 50,
  meet_of: 30,
  project_of: 0,
  all_of: 100,
});
// 处理占比计算问题
// 计算属性，用于计算all_of的值
// const allOf = computed({
//   get: () => formState.write_of + formState.practe_of + formState.meet_of + formState.project_of,
//   set: (newValue) => {
//     // 如果需要，你可以在这里处理设置all_of时的逻辑
//     console.log("all_of set to", newValue);
//   }
// });
// 监听write_of, practe_of, meet_of, project_of的变化，计算all_of的值
watch(
  () => [
    formState.write_of,
    formState.practe_of,
    formState.meet_of,
    formState.project_of,
  ],
  (
    [newWriteOf, newPracteOf, newMeetOf, newProjectOf],
    [oldWriteOf, oldPracteOf, oldMeetOf, oldProjectOf]
  ) => {
    console.log(`write_of changed from ${oldWriteOf} to ${newWriteOf}`);
    console.log(`praote_of changed from ${oldPracteOf} to ${newPracteOf}`);
    console.log(`meet_of changed from ${oldMeetOf} to ${newMeetOf}`);
    console.log(`project_of changed from ${oldProjectOf} to ${newProjectOf}`);
    // 更新all_of的值
    // formState.all_of = Number(newWriteOf) + Number(newPracteOf) + Number(newMeetOf) + Number(newProjectOf);
    formState.all_of = newWriteOf + newPracteOf + newMeetOf + newProjectOf;
  }
);
// ........
// 规则--修改和添加用一样的接口
const rules: Record<string, Rule[]> = {
  name: [
    { required: true, message: "请输入权限名字", trigger: "change" },
    { min: 2, max: 50, message: "长度为2到50个字符串", trigger: "blur" },
  ],
  type: [{ required: true, message: "请选择考试类型", trigger: "change" }],
  class_id: [{ required: true, message: "请选择班级", trigger: "change" }],
  date: [{ required: true, message: "请输入考试时间", trigger: "change" }],
  notes: [
    { required: true, message: "请输入考试备注", trigger: "change" },
    { min: 3, message: "长度最少为3个字符串", trigger: "blur" },
  ],
  //   total_score: [
  //     { required: true, message: "请输入考试总分", trigger: "change" },
  //   ],
};
// 对话窗中的取消按钮
const handleCancel = () => {
  open_add.value = false;
};
// 添加按钮
const showModal_add = () => {
  open_add.value = true;
};
// 对话窗中的确定按钮
const handleSubmit = () => {
  formRef.value
    .validate()
    .then(() => {
      console.log("values", formState, toRaw(formState));
      open_add.value = false;
      // 添加用户的接口
      add_exam();
    })
    .catch((error: any) => {
      console.log("error", error);
    });
};
// 3. 表格中的一系列操作及数据
type Key = string | number;
// 表头
const columns = [
  {
    title: "考试名称",
    dataIndex: "name",
    key: "name",
    width: 160,
  },
  {
    title: "考试类型",
    dataIndex: "type",
    key: "type",
    width: 100,
  },
  {
    title: "专业",
    dataIndex: "program_name",
    key: "program_name",
    width: 120,
  },
  {
    title: "班级",
    dataIndex: "class_name",
    key: "class_name",
    width: 120,
  },{
    title: "出题人",
    dataIndex: "teacher_name",
    key: "teacher_name",
    width: 120,
  },
  {
    title: "考试日期",
    dataIndex: "date",
    key: "date",
    width: 160,
  },
  {
    title: "已录入总数",
    dataIndex: "student_count",
    key: "student_count",
    width: 120,
  },
  {
    title: "平均分",
    dataIndex: "average_score",
    key: "average_score",
    width: 120,
  },
  {
    title: "总分",
    dataIndex: "total_score",
    key: "total_score",
    width: 120,
  },
  {
    title: "操作",
    key: "action",
    width: 280,
  },
];
// 表中数据
const dataSource = ref<string[]>([]);
const loading = ref(false); // 表格的加载
// 勾选框的一系列操作
const state = reactive<{
  selectedRowKeys: Key[];
  loading: boolean;
  pageSize: number;
  total: number;
  current: number;
}>({
  selectedRowKeys: [],
  loading: false,
  pageSize: 10,
  total: 100,
  current: 1,
});
// 请求后端列表接口
const test_list = async () => {
  console.log("exam_dateexam_dateexam_dateexam_date::", exam_date.value);
  try {
    loading.value = true; // 开始加载
    const response = await http.get("/api/tests/list", {
      params: {
        // name, class_id, program_id, date, type, page, page_size
        name: exam_name.value.trim(),
        class_id: class_id.value,
        program_id: program_id.value,
        start_date: exam_date.value[0]
          ? dayjs(exam_date.value[0]).format("YYYY-MM-DD HH:mm:ss")
          : null,
        end_date: exam_date.value[1]
          ? dayjs(exam_date.value[1]).format("YYYY-MM-DD HH:mm:ss")
          : null,
        type: exam_type.value,
        page_size: state.pageSize,
        page: state.current,
      },
    });
    // console.log(response.data.data)
    const exams = response.data.results.exams;
    // 为每个用户对象添加一个唯一的 key 值，这里使用用户的 id 作为 key
    dataSource.value = exams.map((exam: any, index: any) => {
      return {
        ...exam,
        date: dayjs(exam.date).format("YYYY-MM-DD HH:mm:ss"),
        key: exam.id, // 确保每个对象都有一个唯一的 key 值
      };
    });
    state.total = response.data.results.total;
  } catch (error) {
    console.log("请求失败：：", error);
  } finally {
    loading.value = false; // 开始加载
  }
};

// 4. 修改用户一系列操作
// 修改用户--保存数据
const edit_id = ref<number>(); // 修改的id
// 表单元素
const formState_edit: UnwrapRef<FormState> = reactive({
  name: "",
  type: null,
  class_id: null,
  date: "",
  notes: "",
  total_score: "",
  write_of: 20,
  practe_of: 50,
  meet_of: 30,
  project_of: 0,
  all_of: 100,
  class_name: "",
});
// 修改-设置数据接口
const edit_save = async () => {
  try {
    const response = await http.post("/api/tests/set", {
      id: edit_id.value,
      name: formState_edit.name,
      type: formState_edit.type,
      class_id: formState_edit.class_id,
      date: dayjs(formState_edit.date).format("YYYY-MM-DD HH:mm:ss"),
      notes: formState_edit.notes,
      total_score: formState_edit.total_score,
      write_of: formState_edit.write_of,
      practe_of: formState_edit.practe_of,
      meet_of: formState_edit.meet_of,
      project_of: formState_edit.project_of,
    });
    if (response.data.code === 0) {
      test_list();
      message.success(response.data.msg);
    } else {
      message.error(response.data.msg);
    }
  } catch (error) {
    console.log("请求失败：：", error);
  }
};
// 弹窗的关闭与否
const open_edit = ref<boolean>(false);
const formRef_edit = ref();
// 修改用户--获取数据
const get_info = async (id: number) => {
  try {
    const response = await http.get("/api/tests/get", {
      params: {
        id: id,
      },
    });
    formState_edit.name = response.data.results[0].name;
    formState_edit.type = response.data.results[0].type;
    formState_edit.class_id = response.data.results[0].class_id;
    formState_edit.date = dayjs(response.data.results[0].date);
    formState_edit.notes = response.data.results[0].notes;
    formState_edit.total_score = response.data.results[0].total_score;
    formState_edit.write_of = response.data.results[0].write_of;
    formState_edit.practe_of = response.data.results[0].practe_of;
    formState_edit.meet_of = response.data.results[0].meet_of;
    formState_edit.project_of = response.data.results[0].project_of;
    formState_edit.class_name = response.data.results[0].class_name;

    edit_id.value = response.data.results[0].id;
  } catch (error) {
    console.log("请求失败：：", error);
  }
};
// 打开谈话窗的按钮方法
const showModal_edit = async (id: number) => {
  // console.log(id)
  open_edit.value = true;
  get_info(id);
};
// 谈话框中点击确定的时候方法
const handleOk_edit = () => {
  formRef_edit.value
    .validate()
    .then(() => {
      console.log("values", formState_edit, toRaw(formState_edit));
      open_edit.value = false;
      // 修改考试--保存数据
      edit_save();
    })
    .catch((error: any) => {
      console.log("error", error);
    });
};
// 抽屉的取消按钮
const handleCancel_edit = () => {
  open_edit.value = false;
};
// 统计当前考试的总数
const total_count = async (row: any) => {
  try {
    // 添加确认对话框
    Modal.confirm({
      title: "统计当前考试总数",
      content: "确定要统计该考试已录入成绩的总分数据吗？",
      okText: "确认",
      cancelText: "取消",
      onOk: async () => {
        try {
          const res = await http.get("/api/tests/total_count", {
            params: {
              exam_id: row.id,
              class_id: row.class_id,
            },
          });

          if (res.data.code === 0) {
            console.log("统计总数成功：", res);
            test_list(); // 刷新列表
            message.success(res.data.msg);
          } else {
            message.error(res.data.msg);
          }
        } catch (error) {
          console.log("请求出错：", error);
          message.error("统计过程中发生错误");
        }
      },
      onCancel: () => {
        console.log("用户取消统计");
      },
    });
  } catch (error) {
    console.log("对话框出错：", error);
  }
};

// 统计当前考试的平均数
const count_average = async (row: any) => {
  console.log("统计当前考试的平均数", row);
  try {
    // 添加确认对话框
    Modal.confirm({
      title: "确认统计考试平均分",
      content: "确定要统计该考试已录入成绩的平均分数据吗？",
      okText: "确认统计",
      cancelText: "取消",
      async onOk() {
        try {
          const hideLoading = message.loading("正在统计中...", 0);

          const res = await http.get("/api/tests/count_average", {
            params: { exam_id: row.id, class_id: row.class_id },
          });

          hideLoading(); // 关闭加载提示

          if (res.data.code === 0) {
            console.log("统计平均数成功：", res);
            test_list(); // 刷新列表
            message.success(res.data.msg);
          } else {
            message.error(res.data.msg);
          }
        } catch (error) {
          console.error("统计出错：", error);
          message.error("统计过程中发生错误");
        }
      },
      onCancel() {
        console.log("用户取消统计平均分");
      },
    });
  } catch (error) {
    console.error("对话框出错：", error);
  }
};

// 5. 查看用户一系列操作
const open_view = ref<boolean>(false);
const showModal_view = (id: number) => {
  open_view.value = true;
  get_info(id);
};
// 6. 考试记录--成绩统计
// 控制抽屉的打开
const open_exam = ref<boolean>(false);
const exam_record = (row: any) => {
  console.log("这一行的信息：：", row);
  open_exam.value = true;
  get_info(row.id);
  data_exam(row.id, row.class_id);
};
// 表中数据
const dataSource_exam = ref<string[]>([]);
// 表头
const columns_exam = [
  {
    title: "学生姓名",
    dataIndex: "student_name",
    key: "student_name",
  },
  {
    title: "学号",
    dataIndex: "student_count",
    key: "student_count",
  },
  {
    title: "笔试成绩",
    dataIndex: "score_write",
    key: "score_write",
  },
  {
    title: "机试成绩",
    dataIndex: "score_practe",
    key: "score_practe",
  },
  {
    title: "面试成绩",
    dataIndex: "score_meet",
    key: "score_meet",
  },
  {
    title: "项目成绩",
    dataIndex: "score_project",
    key: "score_project",
  },
  {
    title: "总分",
    dataIndex: "score_all",
    key: "score_all",
  },
];
// 考试记录后端数据
const data_exam = async (id: number, class_id: number) => {
  try {
    const response = await http.get("/api/tests/count", {
      params: {
        id: id,
        class_id: class_id,
        page: state2.current,
        page_size: state2.pageSize,
      },
    });
    const exams = response.data.results.results;
    dataSource_exam.value = exams.map((exam, index) => {
      return {
        ...exam,
        key: exam.id, // 确保每个对象都有一个唯一的 key 值
      };
    });
    state2.total = response.data.results.total_count;
  } catch (error) {
    console.log("请求失败：：", error);
  }
};
// 勾选框的一系列操作
const state2 = reactive<{
  selectedRowKeys: Key[];
  loading: boolean;
  pageSize: number;
  total: number;
  current: number;
}>({
  selectedRowKeys: [],
  loading: false,
  pageSize: 10,
  total: 100,
  current: 1,
});
// 7. 成绩录入
// 成绩录入的考试的id
const exam_id = ref<number>();
// 控制抽屉的打开
const open_count = ref<boolean>(false);
// 成绩录入按钮
const count_record = (row: any) => {
  exam_id.value = row.id;
  open_count.value = true;
  console.log("77777777777", row, row.class_id);
  // // 抽屉中的考试信息--所以调用此方法
  get_info(row.id);
  data_count(row.class_id, row.id);
};
// 表中数据
const dataSource_count = ref<string[]>([]);
// 表格中输入框的v-model的值
const score_write = ref<number>();
const score_practe = ref<number>();
const score_meet = ref<number>();
const score_project = ref<number>();
const score_comment = ref<string>("");
// 确定录入的按钮
const enter_count = (row: any) => {
  score_write.value = row.score_write;
  score_practe.value = row.score_practe;
  score_meet.value = row.score_meet;
  score_project.value = row.score_project;
  score_comment.value = row.comment;
  console.log(row, row.score_write, row.student_id, row.student_name);
  Modal.confirm({
    title: `你确定要将学生:${row.student_name}的成绩录入吗？`,
    icon: createVNode(ExclamationCircleOutlined),
    content: createVNode("div", { style: "color:red;" }, "点击确定就会执行"),
    onOk() {
      console.log(
        "确定 准备提交的数据：：",
        exam_id.value,
        row.student_id,
        score_write.value,
        score_practe.value,
        score_meet.value,
        score_project.value,
        score_comment.value
      );
      // 成功时候调用成绩录入的方法
      score_count(row.student_id);
    },
    onCancel() {
      console.log("取消");
    },
    class: "test",
  });
};
// 表头
const columns_count = [
  {
    title: "学生姓名",
    dataIndex: "student_name",
    key: "student_name",
  },
  {
    title: "学号",
    dataIndex: "student_count",
    key: "student_count",
  },
  {
    title: "笔试成绩",
    dataIndex: "score_write",
    key: "score_write",
  },
  {
    title: "机试成绩",
    dataIndex: "score_practe",
    key: "score_practe",
  },
  {
    title: "面试成绩",
    dataIndex: "score_meet",
    key: "score_meet",
  },
  {
    title: "项目成绩",
    dataIndex: "score_project",
    key: "score_project",
  },
  {
    title: "评语",
    dataIndex: "comment",
    key: "comment",
  },
  {
    title: "操作",
    key: "action",
  },
];
// 考试记录后端数据--接口：通过class_id得到的学生信息的接口
const data_count = async (class_id: number, id: number) => {
  try {
    const response = await http.get("/api/tests/exam_student", {
      params: {
        class_id: class_id,
        exam_id: id,
        page: state3.current,
        page_size: state3.pageSize,
      },
    });
    const exams = response.data.results.results;
    // 表格中数据
    dataSource_count.value = exams.map((exam, index) => {
      return {
        ...exam,
        key: exam.student_id, // 确保每个对象都有一个唯一的 key 值
      };
    });
    state3.total = response.data.results.total_count;
  } catch (error) {
    console.log("请求失败：：", error);
  }
};
// 勾选框的一系列操作
const state3 = reactive<{
  selectedRowKeys: Key[];
  loading: boolean;
  pageSize: number;
  total: number;
  current: number;
}>({
  selectedRowKeys: [],
  loading: false,
  pageSize: 10,
  total: 100,
  current: 1,
});
// 学生成绩录入的接口
const score_count = async (student_id: number) => {
  try {
    const response = await http.post("/api/tests/enter", {
      id: exam_id.value,
      student_id: student_id,
      score_write: score_write.value,
      score_practe: score_practe.value,
      score_meet: score_meet.value,
      score_project: score_project.value,
      comment: score_comment.value,
    });
    console.log(response);
    message.success(response.data.msg);
  } catch (error) {
    console.log("请求失败：：", error);
  }
};
// 8. 考试记录的软删除
const del_exam_f = (id: number) => {
  // 删除用户的对话框
  Modal.confirm({
    title: "禁用考试",
    icon: createVNode(ExclamationCircleOutlined),
    content: "您确定要禁用此考试吗？",
    okText: "确定",
    okType: "danger",
    cancelText: "取消",
    async onOk() {
      console.log("OK");
      // 删除的接口
      try {
        const response = await http.get("/api/tests/del_f", {
          params: {
            id: id,
          },
        });
        console.log(response);
        const msg = response.data.msg;
        message.success(msg);
        // 删除成功时候调用列表
        test_list();
      } catch (error) {
        console.log("请求失败：：", error);
      }
    },
    onCancel() {
      console.log("Cancel");
    },
  });
};
const start_state = async (id: number) => {
  try {
    const response = await http.get("/api/tests/start", {
      params: {
        id: id,
      },
    });
    console.log(response);
    const msg = response.data.msg;
    message.success(msg);
    // 删除成功时候调用列表
    test_list();
  } catch (error) {
    console.log("请求失败：：", error);
  }
};
// 9. 考试记录的真删除
const del_exam_t = (id: number) => {
  // 删除用户的对话框
  Modal.confirm({
    title: "删除考试记录",
    icon: createVNode(ExclamationCircleOutlined),
    content: "您确定要删除此记录吗？",
    okText: "确定",
    okType: "danger",
    cancelText: "取消",
    async onOk() {
      console.log("OK");
      // 删除的接口
      try {
        const response = await http.get("/api/tests/del_t", {
          params: {
            id: id,
          },
        });
        console.log(response);
        const msg = response.data.msg;
        message.success(msg);
        // 删除成功时候调用列表
        test_list();
      } catch (error) {
        console.log("请求失败：：", error);
      }
    },
    onCancel() {
      console.log("Cancel");
    },
  });
};

// 生命周期函数
onMounted(() => {
  all_class();
  all_program();
  test_list();
});
</script>

<style scoped>
:deep(:where(.css-dev-only-do-not-override-1p3hq3p).ant-btn > .anticon + span),
:deep(:where(.css-dev-only-do-not-override-1p3hq3p).ant-btn > span + .anticon) {
  margin-inline-start: 0px;
}
</style>